package com.cxc.zk.distributed.demo;

import org.I0Itec.zkclient.IZkDataListener;

import java.util.concurrent.CountDownLatch;

public class ZkDistrbuteLock  extends ZkAbstractLock{
    @Override
    protected void waitLock() {
        // 使用zk临时事件监听
        IZkDataListener iZkDataListener = new IZkDataListener() {
            @Override
            public void handleDataChange(String s, Object o) throws Exception {
                if (countDownLatch != null) {
                    countDownLatch.countDown();
                }
            }
            @Override
            public void handleDataDeleted(String s) throws Exception {

            }
        };
        // 注册事件通知
        zkClient.subscribeDataChanges(lockPath, iZkDataListener);
        if (zkClient.exists(lockPath)) {
            countDownLatch = new CountDownLatch(1);
            try {
                countDownLatch.await();
            } catch (Exception e) {

            }
        }
        // 监听完毕后，移除事件通知
        zkClient.unsubscribeDataChanges(lockPath, iZkDataListener);
    }

    @Override
    protected boolean tryLock() {

        try {
            zkClient.createEphemeral(lockPath);
            return true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }
}
